package com.venus.common.utils;

public class ConditionUtil {
	
	// 条件类型
	private String conditionType;
	// 字段名称
	private String fieldName;
	// 表达式符号
	private String expression;
	// 值
	private String fieldValue;
	// 值是否被''包围
	private boolean isHaveComma;
	
	public ConditionUtil(){
		
	}
	
	public ConditionUtil(String conditionType, String fieldName, String expression, String fieldValue, boolean isHaveComma){
		this.conditionType = conditionType;
		this.fieldName = fieldName;
		this.expression = expression;
		this.fieldValue = fieldValue;
		this.isHaveComma = isHaveComma;
	}
	
	/**
	 * 把条件实例转换成hql
	 * @return
	 */
	public String parse2Hql(){
		StringBuffer sb = new StringBuffer(32);
		// 根据当前实例的条件类型生成hql条件语句
		if("and".equals(this.conditionType)){ // AND条件
			sb.append(" ");
			sb.append(this.conditionType).append(" ");
			sb.append(this.fieldName);
			sb.append(this.expression);
			if(this.isHaveComma){
				sb.append("'").append(this.fieldValue).append("'");
			}else{
				sb.append(this.fieldValue);
			}	
		}else if("or".equals(this.conditionType)){ // OR条件
			sb.append(" ");
			sb.append(this.conditionType).append(" ");
			sb.append(this.fieldName);
			sb.append(this.expression);
			if(this.isHaveComma){
				sb.append("'").append(this.fieldValue).append("'");
			}else{
				sb.append(this.fieldValue);
			}	
		}else if("between".equals(this.conditionType)){ // BETWEEN条件
			sb.append(" and ");
			sb.append(this.fieldName).append(" ");
			sb.append(this.conditionType).append(" ");
			// 分隔参数
			String[] strFieldValues = this.fieldValue.split(",");
			if(this.isHaveComma){
				sb.append("'").append(strFieldValues[0]).append("' ");
				sb.append("and ");
				sb.append("'").append(strFieldValues[1]).append("' ");
			}else{
				sb.append(strFieldValues[0]);
				sb.append("and ");
				sb.append(strFieldValues[1]);
			}
		}else if("order by".equals(this.conditionType)){ // ORDER排序
			sb.append(" ");
			sb.append(this.conditionType).append(" ");
			sb.append(this.fieldName).append(" ");
			sb.append(this.fieldValue);
		}else if("group".equals(this.conditionType)){ // GROUP
			sb.append(" group by ");
			sb.append(this.fieldName).append(" ");
		}
		
		return sb.toString();
	}
}
